<template>
  <div class="min-h-screen bg-gradient-to-br from-green-600 via-teal-600 to-cyan-600 flex items-center justify-center p-4">
    <GameHeader>
      <div class="stats-card">
        <span>得分</span>
        <span class="animate-pulse">{{ score }}</span>
      </div>
      <div class="stats-card">
        <span>时间</span>
        <span class="animate-pulse">{{ formatTime(timeLeft) }}</span>
      </div>
      <div class="stats-card">
        <span>最高分</span>
        <span>{{ highScore }}</span>
      </div>
    </GameHeader>

    <div class="w-[600px] bg-white/10 backdrop-blur-lg rounded-2xl p-8 shadow-2xl border border-white/20">
      <h1 class="text-4xl font-extrabold text-center mb-6 text-white">
        垃圾分类大挑战
        <div class="text-base font-normal mt-2 text-white/80">保护环境，从分类开始！</div>
      </h1>

      <div v-if="!gameStarted" class="text-center space-y-6">
        <button 
          @click="startGame" 
          class="game-button bg-gradient-to-r from-green-500 to-green-700"
        >
          开始游戏
        </button>
        <div class="bg-white/10 rounded-lg p-4">
          <p class="text-xl text-white">最高分：{{ highScore }}</p>
        </div>
      </div>

      <div v-else-if="gameStarted && !gameEnded" class="space-y-6">
        <!-- 垃圾桶区域 -->
        <div class="grid grid-cols-2 gap-4">
          <div v-for="(bin, index) in bins" :key="index" 
               class="bin-container h-32 border-4 rounded-xl flex flex-col items-center justify-center transition-all duration-300 transform hover:scale-105"
               :class="binColors[bin]"
               @dragover.prevent
               @drop="handleDrop($event, bin)">
            <img :src="getBinImage(bin)" :alt="bin" class="w-12 h-12 mb-2">
            <p class="text-lg font-bold text-white">{{ bin }}</p>
          </div>
        </div>

        <!-- 垃圾区域 -->
        <div class="bg-white/10 border border-white/20 rounded-xl p-4 min-h-[120px]">
          <div class="flex flex-wrap justify-center gap-4">
            <div v-for="item in currentTrashItems" :key="item.id"
                 class="trash-item w-16 h-16 bg-white/20 rounded-full flex items-center justify-center cursor-move"
                 draggable="true"
                 @dragstart="dragStart($event, item)">
              <img :src="item.image" :alt="item.name" class="w-12 h-12">
            </div>
          </div>
        </div>
      </div>

      <!-- 游戏结束界面 -->
      <GameOver
        v-if="gameEnded"
        title="🌍 环保任务完成！"
        @restart="restartGame"
      >
        <p class="text-xl text-gray-700">最终得分：{{ score }}</p>
        <p class="text-lg text-gray-600">分类准确率：{{ accuracy.toFixed(2) }}%</p>
      </GameOver>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import GameHeader from './common/GameHeader.vue'
import GameOver from './common/GameOver.vue'

const bins = ['可回收物', '有害垃圾', '厨余垃圾', '其他垃圾']
const binColors = {
  '可回收物': 'border-blue-500 bg-blue-100',
  '有害垃圾': 'border-red-500 bg-red-100',
  '厨余垃圾': 'border-green-500 bg-green-100',
  '其他垃圾': 'border-gray-500 bg-gray-100'
}
const binTextColors = {
  '可回收物': 'text-blue-700',
  '有害垃圾': 'text-red-700',
  '厨余垃圾': 'text-green-700',
  '其他垃圾': 'text-gray-700'
}

const trashItems = [
  { id: 1, name: '塑料瓶', type: '可回收物', image: '/placeholder.svg?height=50&width=50' },
  { id: 2, name: '电池', type: '有害垃圾', image: '/placeholder.svg?height=50&width=50' },
  { id: 3, name: '香蕉皮', type: '厨余垃圾', image: '/placeholder.svg?height=50&width=50' },
  { id: 4, name: '烟头', type: '其他垃圾', image: '/placeholder.svg?height=50&width=50' },
  { id: 5, name: '纸张', type: '可回收物', image: '/placeholder.svg?height=50&width=50' },
  { id: 6, name: '过期药品', type: '有害垃圾', image: '/placeholder.svg?height=50&width=50' },
  { id: 7, name: '果皮', type: '厨余垃圾', image: '/placeholder.svg?height=50&width=50' },
  { id: 8, name: '餐巾纸', type: '其他垃圾', image: '/placeholder.svg?height=50&width=50' },
  // 可以继续添加更多垃圾项目...
]

const gameStarted = ref(false)
const gameEnded = ref(false)
const score = ref(0)
const timeLeft = ref(60)
const level = ref(1)
const currentTrashItems = ref([])
const totalAttempts = ref(0)
const correctAttempts = ref(0)
const highScore = ref(0)

const accuracy = computed(() => {
  return totalAttempts.value === 0 ? 0 : (correctAttempts.value / totalAttempts.value) * 100
})

let timer

const sounds = {
  correct: new Audio('/audio/correct.wav'),
  wrong: new Audio('/audio/wrong.wav'),
  start: new Audio('/audio/start.wav'),
  end: new Audio('/audio/end.wav')
}

const playSound = (soundName) => {
  try {
    sounds[soundName].currentTime = 0
    sounds[soundName].play()
  } catch (error) {
    console.warn('音效播放失败:', error)
  }
}

const startGame = () => {
  gameStarted.value = true
  gameEnded.value = false
  score.value = 0
  timeLeft.value = 60
  level.value = 1
  totalAttempts.value = 0
  correctAttempts.value = 0
  generateTrashItems()
  startTimer()
  playSound('start')
}

const generateTrashItems = () => {
  const itemCount = Math.min(4 + level.value, 8)
  currentTrashItems.value = []
  for (let i = 0; i < itemCount; i++) {
    const randomItem = trashItems[Math.floor(Math.random() * trashItems.length)]
    currentTrashItems.value.push({ ...randomItem, id: Date.now() + i })
  }
}

const startTimer = () => {
  timer = setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--
    } else {
      endGame()
    }
  }, 1000)
}

const endGame = () => {
  clearInterval(timer)
  gameEnded.value = true
  playSound('end')
  if (score.value > highScore.value) {
    highScore.value = score.value
    localStorage.setItem('trashGameHighScore', highScore.value)
  }
}

const restartGame = () => {
  gameStarted.value = false
  gameEnded.value = false
}

const formatTime = (time) => {
  const minutes = Math.floor(time / 60)
  const seconds = time % 60
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

const dragStart = (event, item) => {
  event.dataTransfer.setData('text/plain', JSON.stringify(item))
}

const touchStart = (event, item) => {
  event.preventDefault()
  const touch = event.touches[0]
  const dropTarget = document.elementFromPoint(touch.clientX, touch.clientY)
  if (dropTarget && dropTarget.classList.contains(binColors[item.type].split(' ')[0])) {
    handleDrop(item, item.type)
  }
}

const handleDrop = (item, binType) => {
  totalAttempts.value++
  if (item.type === binType) {
    score.value += 10
    correctAttempts.value++
    timeLeft.value = Math.min(timeLeft.value + 5, 60)
    playSound('correct')
  } else {
    score.value = Math.max(0, score.value - 5)
    timeLeft.value = Math.max(0, timeLeft.value - 3)
    playSound('wrong')
  }
  currentTrashItems.value = currentTrashItems.value.filter(i => i.id !== item.id)
  if (currentTrashItems.value.length === 0) {
    level.value++
    generateTrashItems()
  }
}

const showHint = () => {
  score.value = Math.max(0, score.value - 10)
  alert('提示：仔细观察垃圾的材质和用途，根据它们的特性来判断应该放入哪个垃圾桶。可回收物通常是可以再利用的物品，有害垃圾对环境有害，厨余垃圾是可降解的食物残渣，其他垃圾则是不属于前三类的垃圾。')
}

const getBinImage = (binType) => {
  switch (binType) {
    case '可回收物':
      return '/placeholder.svg?height=80&width=80'
    case '有害垃圾':
      return '/placeholder.svg?height=80&width=80'
    case '厨余垃圾':
      return '/placeholder.svg?height=80&width=80'
    case '其他垃圾':
      return '/placeholder.svg?height=80&width=80'
    default:
      return '/placeholder.svg?height=80&width=80'
  }
}

onMounted(() => {
  const savedHighScore = localStorage.getItem('trashGameHighScore')
  if (savedHighScore) {
    highScore.value = parseInt(savedHighScore)
  }

  bins.forEach(bin => {
    const binElements = document.querySelectorAll(`.${binColors[bin].split(' ')[0]}`)
    binElements.forEach(binElement => {
      if (binElement) {
        binElement.addEventListener('dragover', (e) => e.preventDefault())
        binElement.addEventListener('drop', (e) => {
          e.preventDefault()
          const item = JSON.parse(e.dataTransfer.getData('text/plain'))
          handleDrop(item, bin)
        })
      }
    })
  })

  Object.values(sounds).forEach(sound => {
    sound.load()
    sound.volume = 0.6
  })
})

onUnmounted(() => {
  clearInterval(timer)
})
</script>

<style scoped>
.bin-container {
  @apply relative overflow-hidden;
  transition: all 0.3s ease;
}

.bin-container::before {
  content: '';
  @apply absolute inset-0 bg-white/10 opacity-0 transition-opacity duration-300;
}

.bin-container:hover::before {
  @apply opacity-100;
}

.trash-item {
  @apply transition-all duration-300 hover:scale-110 hover:shadow-lg;
}

.trash-item img {
  @apply transition-transform duration-300;
}

.trash-item:hover img {
  transform: scale(1.1);
}

/* 动画效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.trash-item-move {
  transition: all 0.5s ease;
}

.trash-item-enter-active,
.trash-item-leave-active {
  transition: all 0.5s ease;
}

.trash-item-enter-from,
.trash-item-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

.game-button {
  @apply px-6 py-3 text-white font-bold rounded-lg shadow-lg hover:scale-105 transition duration-300;
}
</style>